package org.study.hadoop.md.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 日期格式化工具类
 */
public class DateUtil {
	private DateUtil() {}
	private static final String PATTERN_ALL = "yyyy-MM-dd HH:mm:ss";	//复杂日期格式
	private static final String PATTERN_SIMPLE = "yyyy-MM-dd";			//简单日期格式
	/**
	 * 复杂日期格式化
	 * @param date
	 * @return yyyy-MM-dd HH:mm:ss
	 */
	public static String formatDateAll(Date date) {
		DateFormat dateFormat = new SimpleDateFormat(PATTERN_ALL);
		return dateFormat.format(date); 
	}
	/**
	 * 简单日期格式化
	 * @param date
	 * @return yyyy-MM-dd
	 */
	public static String formatDateSimple(Date date) {
		DateFormat dateFormat = new SimpleDateFormat(PATTERN_SIMPLE);
		return dateFormat.format(date);
	}
	/**
	 * 复杂日期字符串转日期
	 * @param str yyyy-MM-dd HH:mm:ss
	 * @return date
	 * @throws ParseException 
	 */
	public static Date formatStringAll(String str) {
		DateFormat dateFormat = new SimpleDateFormat(PATTERN_ALL);
		try {
			return dateFormat.parse(str);
		} catch (ParseException e) {
			return null;
		}
	}
	/**
	 * 简单日期字符串转日期
	 * @param str yyyy-MM-dd
	 * @return date
	 * @throws ParseException 
	 */
	public static Date formatStringSimple(String str) throws ParseException {
		DateFormat dateFormat = new SimpleDateFormat(PATTERN_SIMPLE);
		return dateFormat.parse(str);
	}
	
	public static Date randomDate(String beginDate,String endDate){  
        try {  
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
            Date start = format.parse(beginDate);  
            Date end = format.parse(endDate);  
              
            if(start.getTime() >= end.getTime()){  
                return null;  
            }  
              
            long date = random(start.getTime(),end.getTime());  
              
            return new Date(date);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
      
    private static long random(long begin,long end){  
        long rtn = begin + (long)(Math.random() * (end - begin));  
        if(rtn == begin || rtn == end){  
            return random(begin,end);  
        }  
        return rtn;  
    }  
}
